package com.example.demo.dao.impl;

import com.example.demo.dao.BaseDaoImpl;
import com.example.demo.dao.IVirtualDao;
import com.example.demo.model.po.VirtualPage;
import com.example.demo.model.request.VirtualPageRequest;
import com.example.demo.util.AssertUtils;
import com.example.demo.util.DateUtils;
import org.jooq.Condition;
import org.jooq.Record;
import org.jooq.SelectJoinStep;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.example.demo.jooq.tables.Virtual.VIRTUAL;
import static org.jooq.impl.DSL.count;

@Component
public class IVirtualDaoImpl extends BaseDaoImpl implements IVirtualDao {


    @Override
    public List<VirtualPage> queryPageVirtualList(VirtualPageRequest virtualPageRequest) {
        //查询条件
        List<Condition> conditions = new ArrayList<>();
        if(AssertUtils.isNotEmpty(virtualPageRequest.getKeyword())){
            conditions.add(VIRTUAL.VIRTUAL_NAME.likeRegex(virtualPageRequest.getKeyword().trim())
                                    .or(VIRTUAL.SERVICE_NAME.likeRegex(virtualPageRequest.getKeyword().trim()))
            );
        }
        if(AssertUtils.isNotEmpty(virtualPageRequest.getVirtualStatus())){
            conditions.add(VIRTUAL.VIRTUAL_STATUS.likeRegex(virtualPageRequest.getVirtualStatus()));
        }
        if(AssertUtils.isNotEmpty(virtualPageRequest.getCreatedDate())){
            conditions.add(VIRTUAL.CREATED_DATE.eq(DateUtils.stringToTime(virtualPageRequest.getCreatedDate())));
        }
        if(AssertUtils.isNotEmpty(virtualPageRequest.getServiceName())){
            conditions.add(VIRTUAL.SERVICE_NAME.eq(virtualPageRequest.getServiceName()));
        }
        if(AssertUtils.isNotEmpty(virtualPageRequest.getVirtualName())){
            conditions.add(VIRTUAL.VIRTUAL_NAME.eq(virtualPageRequest.getVirtualName()));
        }
        if(AssertUtils.isNotEmpty(virtualPageRequest.getServiceUser())){
            conditions.add(VIRTUAL.SERVICE_USER.eq(virtualPageRequest.getServiceUser()));
        }
        if(AssertUtils.isNotEmpty(virtualPageRequest.getSite())){
            conditions.add(VIRTUAL.SITE.eq(virtualPageRequest.getSite()));
        }
        SelectJoinStep<Record> totalLine = this.getDslContext()
                .select(VIRTUAL.fields())
                .select(count().over().as("totalLine"))
                .from(VIRTUAL);
        totalLine.where(conditions);
        return totalLine.orderBy(VIRTUAL.CREATED_DATE.desc())
                .offset(virtualPageRequest.getOffset())
                .limit(virtualPageRequest.getPageSize())
                .fetchInto(VirtualPage.class);
    }
}
